<template>
  <div class="FlipClock" data-tauri-drag-region>
    <Flipper ref="flipperHour1" />
    <Flipper ref="flipperHour2" />
    <em>:</em>
    <Flipper ref="flipperMinute1" />
    <Flipper ref="flipperMinute2" />
    <em>:</em>
    <Flipper ref="flipperSecond1" />
    <Flipper ref="flipperSecond2" />
  </div>
</template>

<script>
import Flipper from './Flipper.vue'

export default {
  name: 'FlipClock',
  data() {
    return {
      timer: null,
      flipObjs: []
    }
  },
  components: {
    Flipper
  },
  methods: {
    // 初始化数字
    init() {
      let now = new Date()
      let nowTimeStr = this.formatDate(new Date(now.getTime()), 'hhiiss')
      for (let i = 0; i < this.flipObjs.length; i++) {
        this.flipObjs[i].setFront(nowTimeStr[i])
      }
    },
    // 开始计时
    run() {
      this.timer = setInterval(() => {
        // 获取当前时间
        let now = new Date()
        let nowTimeStr = this.formatDate(new Date(now.getTime() - 1000), 'hhiiss')
        let nextTimeStr = this.formatDate(now, 'hhiiss')
        for (let i = 0; i < this.flipObjs.length; i++) {
          if (nowTimeStr[i] === nextTimeStr[i]) {
            continue
          }
          this.flipObjs[i].flipDown(
            nowTimeStr[i],
            nextTimeStr[i]
          )
        }
      }, 1000)
    },

    // 正则格式化日期 2024.4.15
    formatDate(date, dateFormat) {
      const yearRegex = /(y+)/g;
      let yearMatch;
      while ((yearMatch = yearRegex.exec(dateFormat)) !== null) {
        const yearString = (date.getFullYear() + '').slice(-yearMatch[1].length);
        dateFormat = dateFormat.replace(yearMatch[0], yearString);
      }

      const regexps = {
        'm+': date.getMonth() + 1,
        'd+': date.getDate(),
        'h+': date.getHours(),
        'i+': date.getMinutes(),
        's+': date.getSeconds()
      };

      for (let k in regexps) {
        const pattern = new RegExp(`(${k})`, 'g');
        dateFormat = dateFormat.replace(pattern, (match, p1) => {
          const value = regexps[k] + '';
          return p1.length > 1 ? this.padLeftZero(value) : value;
        });
      }
      return dateFormat;
    },

    padLeftZero(str) {
      return ('00' + str).slice(-2);
    }
  },
  mounted() {
    this.flipObjs = [
      this.$refs.flipperHour1,
      this.$refs.flipperHour2,
      this.$refs.flipperMinute1,
      this.$refs.flipperMinute2,
      this.$refs.flipperSecond1,
      this.$refs.flipperSecond2
    ]
    this.init()
    this.run()
  }
}
</script>

<style>
.FlipClock {
  text-align: center;
}

.FlipClock .M-Flipper {
  margin: 0 3px;
}

.FlipClock em {
  display: inline-block;
  line-height: 102px;
  font-size: 66px;
  font-style: normal;
  vertical-align: top;
}
</style>